/*
 * @Author: xmily
 * @Date: 2021-11-09 23:10:10
 * @LastEditors: xmily
 * @LastEditTime: 2022-02-13 03:03:21
 * @FilePath: \glxxapi\jwtauth.js
 * @Description: 
 * 
 * Copyright (c) 2022 by xmily/mxthink.com.cn, All Rights Reserved. 
 */
//用户登录验证过滤器
//options.notcheckpath 不需要验证的具体路径
//options.notcheckdir  不需要验证的目录
const sitecfg = require("./cfg/siteconfig.js");
const jwt = require("jsonwebtoken");

module.exports = (options) => async (ctx, next) => {
  for (index in options.notcheckdir) {
    // eval("/^\"+item+"\/{0,1}$|^\"+item+"(\/.+)+/gm")
    // /^\/test\/{0,1}$|^\/test(\/.+)+/gm
    //正则匹配以下情况:/test|/test/|/test/abc|/test/abc/efg  不匹配以下情况：/abc/test/|/abc/test/efg。可以实现某目录下所有子目录均可匹配
    let reg = new RegExp(
      "^\\" +
        options.notcheckdir[index] +
        "\\/{0,1}$|^\\" +
        options.notcheckdir[index] +
        "(\\/.+)+",
      "gm"
    );
    if (reg.test(ctx.url)) {
      console.log(options.notcheckdir[index] + "该目录下的路径不需要验证");
      await next();
      return;
    }
  }

  for (index in options.notcheckpath) {
    // /^\/wechatforsvr\?.+|^\/wechatforsvr$/gm
    let reg = new RegExp(
      "^\\" +
        options.notcheckpath[index] +
        "\\?.+|^\\" +
        options.notcheckpath[index] +
        "$",
      "gm"
    );
    if (reg.test(ctx.url)) {
      console.log(ctx.url + "该路径不需要验证");
      await next();
      return;
    }
  }
  // if (options.notcheckpath.indexOf(ctx.url) > -1) {
  //     console.log(ctx.url + "该路径不需要验证")
  //     await next();
  //     return;
  // }
  console.log("该路径需要验证:" + ctx.url);

  //验证部分开始
  let token = ctx.header.authorization;
  console.log(token);
  if (ctx.header.authorization) {
    try {
      //验证token合法性
      let token = await jwt.verify(ctx.header.authorization, sitecfg.tokenKey);
      ctx.request.token = token;
    } catch (err) {
      console.log("all验证token时出错：[" + err + "]程序终止!");
      ctx.body = {
        error: true,
        message: "验证token时出错：[" + err + "]程序终止!",
      };
      return;
    }
    await next();
  } else {
    console.log("token验证出错all");
    ctx.body = { error: true, message: "验证token时出错：程序终止!" };
    return;
  }
};
